package com.vercon.common.wifi

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.NetworkInfo
import android.net.wifi.SupplicantState
import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import android.os.Parcelable
import com.vercon.common.mode.event.WifiSuccessEvent
import com.vercon.common.utils.LogUtils
import org.greenrobot.eventbus.EventBus


/**
 * Created by YZC on 2019/7/2
 * 处理wifi广播
 */
class EasyzcWifiReceiver : BroadcastReceiver() {
    val TAG = javaClass.simpleName

    companion object {
        @Volatile
        var preConnect = false
        fun filter() = IntentFilter().also {
            it.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)
            it.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION)
            it.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION)
            it.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)
        }
    }

    override fun onReceive(context: Context?, intent: Intent?) {
        LogUtils.i(TAG, "onReceive: intent action " + intent?.action!!)
        when (intent?.action) {
            WifiManager.SCAN_RESULTS_AVAILABLE_ACTION -> {
                // 当扫描结果后，进行刷新列表
                EasyzcWifi.get().refresh()
            }

            WifiManager.NETWORK_STATE_CHANGED_ACTION -> {
                // 连接状态变化
                EasyzcWifi.get().onNetWorkStateChanged()
                val parcelableExtra = intent.getParcelableExtra<Parcelable>(WifiManager.EXTRA_NETWORK_INFO)
                if (null != parcelableExtra) {
                    // 获取联网状态的NetWorkInfo对象
                    val networkInfo = parcelableExtra as NetworkInfo
                    // 判断网络是否已经连接 <unknown ssid>
                    if ("<unknown ssid>" == networkInfo.extraInfo) {
                        return
                    }
                    if (networkInfo.isConnected && EasyzcWifi.get().enable) {
                        // LogUtils.d(TAG, "连接成功，判断是否可用")
                        // isNetSystemUsable(context)
//                        ToastUtils.showToast(CLang.getContext().getString(R.string.net_work_success))
//                        EasyzcWifi.get().onConnectSuccess(null)
                        EventBus.getDefault().post(WifiSuccessEvent())
                        LogUtils.e("连接成功")
                    } else {
                        EasyzcWifi.get().onConnecting()
                    }
                }
            }
            WifiManager.WIFI_STATE_CHANGED_ACTION -> {
                // wifi的打开与关闭
                val wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_DISABLING)
                wifiState(wifiState)
                LogUtils.d(TAG, "==== onWiFiStateChanged")
            }
            WifiManager.SUPPLICANT_STATE_CHANGED_ACTION -> {
                val linkWifiResult = intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, -1)
                if (linkWifiResult == WifiManager.ERROR_AUTHENTICATING) {
                    // 密码错误
                    preConnect = false
                    LogUtils.d(TAG, "密码错误")

                    EasyzcWifi.get().onConnectFault()
                } else {
                    val supplicantState = intent.getParcelableExtra<SupplicantState>(WifiManager.EXTRA_NEW_STATE)
                    val state = WifiInfo.getDetailedStateOf(supplicantState)
                    detailState(context, state)
                }
            }
        }
    }



    private fun wifiState(wifiState: Int) = when (wifiState) {
        WifiManager.WIFI_STATE_DISABLING -> {
            LogUtils.d(TAG, "正在停止wifi")
//          ToastUtils.showToast("正在停止wifi")
        }
        WifiManager.WIFI_STATE_DISABLED -> {
            LogUtils.d(TAG, "已停止wifi")
//            ToastManager.instance().success("已停止wifi")
        }
        WifiManager.WIFI_STATE_ENABLING -> {
            LogUtils.d(TAG, "正在打开wifi")
//           ToastUtils.showToast("正在打开wifi")
        }
        WifiManager.WIFI_STATE_ENABLED -> {
            LogUtils.d(TAG, "已打开wifi")
//            ToastManager.instance().success("已打开wifi")
        }
        else -> {
        }
    }

    var preDetailState = NetworkInfo.DetailedState.BLOCKED
    private fun detailState(context: Context?, detailedState: NetworkInfo.DetailedState) {
        if (preDetailState == detailedState) {
            LogUtils.d(TAG, "detailedState repeart")
            return
        }
        preDetailState = detailedState
        when (detailedState) {
            NetworkInfo.DetailedState.IDLE -> {
                // 正在连接 准备开始数据连接设置
                LogUtils.d(TAG, "IDLE")
            }
            NetworkInfo.DetailedState.SCANNING ->
                // 正在搜索可用的接入点。
                LogUtils.d(TAG, "SCANNING")
            NetworkInfo.DetailedState.CONNECTING -> {
                // 正在建立数据连接。
                LogUtils.d(TAG, "CONNECTING")
            }
            NetworkInfo.DetailedState.OBTAINING_IPADDR -> {
                // 等待来自DHCP服务器的响应，以便分配IP地址信息。
                LogUtils.d(TAG, "OBTAINING_IPADDR")
                //ToastManager.instance().success("正在获取IP")
            }
            NetworkInfo.DetailedState.CONNECTED ->
                // IP通信应该是可用的。
                LogUtils.d(TAG, "CONNECTED")
            NetworkInfo.DetailedState.SUSPENDED -> {
                // IP流量暂停
                LogUtils.d(TAG, "SUSPENDED")
               // ToastUtils.showToast(CLang.getContext().getString(R.string.net_no_work))
                preConnect = false
            }
            NetworkInfo.DetailedState.DISCONNECTED -> {
                // IP流量不可用。
                LogUtils.d(TAG, "DISCONNECTED")
                EasyzcWifi.get().onDisconnected()
              //  ToastUtils.showToast(CLang.getContext().getString(R.string.net_no_work))
                preConnect = false
            }
            NetworkInfo.DetailedState.DISCONNECTING, NetworkInfo.DetailedState.FAILED -> {
                // 当前正在断开数据连接 | 尝试连接失败
                LogUtils.d(TAG, "FAILED")
                //ToastUtils.showToast(CLang.getContext().getString(R.string.net_work_failed))
                preConnect = false
            }
            else -> {}
        }
    }

}


